package com.unlcn.ils.wms.backend.service.inbound.impl;

import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.HttpRequestUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.unlcn.ils.wms.backend.bo.baseDataBO.VehicleSpecBO;
import com.unlcn.ils.wms.backend.bo.inboundBO.WmsInboundAllocationBO;
import com.unlcn.ils.wms.backend.bo.inboundBO.WmsInboundOrderBO;
import com.unlcn.ils.wms.backend.bo.tmsApi.InboundToTms;
import com.unlcn.ils.wms.backend.dto.inboundDTO.WmsInboundOrderDTO;
import com.unlcn.ils.wms.backend.enums.*;
import com.unlcn.ils.wms.backend.service.borrow.WmsBorrowCarService;
import com.unlcn.ils.wms.backend.service.inbound.AsnOrderService;
import com.unlcn.ils.wms.backend.service.inbound.WmsInboundRepairService;
import com.unlcn.ils.wms.backend.service.outbound.WmsDealerCarBackService;
import com.unlcn.ils.wms.backend.service.outbound.WmsShipmentPlanService;
import com.unlcn.ils.wms.backend.util.InboundExcelUtils;
import com.unlcn.ils.wms.backend.util.ObjectToMapUtils;
import com.unlcn.ils.wms.backend.util.SendMail;
import com.unlcn.ils.wms.backend.util.jpush.JpushClientUtils;
import com.unlcn.ils.wms.base.businessDTO.inbound.AsnOrderDTO;
import com.unlcn.ils.wms.base.businessDTO.inbound.AsnOrderDetailDTO;
import com.unlcn.ils.wms.base.businessDTO.inbound.WmsAsnOrderQueryDTO;
import com.unlcn.ils.wms.base.dto.InboundExcelDTO;
import com.unlcn.ils.wms.base.dto.InboundInfoDTO;
import com.unlcn.ils.wms.base.mapper.additional.WmsAllocationExtMapper;
import com.unlcn.ils.wms.base.mapper.additional.WmsInboundAsnOrderAddMapper;
import com.unlcn.ils.wms.base.mapper.additional.WmsInventoryExtMapper;
import com.unlcn.ils.wms.base.mapper.additional.WmsInventoryLocationExtMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.WmsInboundOrderDetailExtMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.WmsMailConfigExtMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.WmsWarehouseNoticeExtMapper;
import com.unlcn.ils.wms.base.mapper.inbound.WmsAsnTempExpandMapper;
import com.unlcn.ils.wms.base.mapper.inbound.WmsInboundAllocationMapper;
import com.unlcn.ils.wms.base.mapper.inbound.WmsInboundOrderDetailMapper;
import com.unlcn.ils.wms.base.mapper.inbound.WmsInboundOrderMapper;
import com.unlcn.ils.wms.base.mapper.stock.WmsInventoryLocationMapper;
import com.unlcn.ils.wms.base.mapper.stock.WmsMailLogMapper;
import com.unlcn.ils.wms.base.mapper.stock.WmsShipmentPlanMapper;
import com.unlcn.ils.wms.base.mapper.sys.SysUserMapper;
import com.unlcn.ils.wms.base.model.inbound.*;
import com.unlcn.ils.wms.base.model.outbound.WmsDealerCarBack;
import com.unlcn.ils.wms.base.model.stock.*;
import com.unlcn.ils.wms.base.model.sys.SysUser;
import jodd.util.StringUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by DELL on 2017/8/4.
 */
@Service
public class AsnOrderServiceImpl implements AsnOrderService {
    private Logger logger = LoggerFactory.getLogger(AsnOrderServiceImpl.class);

    private static final String TYPE_INBOUND = "1002";//入库收货质检和入库确认推送类别

    @Value("${tms.pickup.host.url}")
    private String propertyUrl;

    @Value("${tms.pickup.host.timeout}")
    private String propertyTime;

    @Value("${tms.encode.key}")
    private String propertyKey;


    @Autowired
    private WmsInboundOrderMapper wmsInboundAsnOrderMapper;

    @Autowired
    private WmsInboundOrderDetailMapper wmsInboundAsnOrderDetailMapper;

    @Autowired
    private WmsInboundAsnOrderAddMapper wmsInboundAsnOrderAddMapper;

    @Autowired
    private WmsAllocationExtMapper wmsAllocationExtMapper;

    @Autowired
    private WmsInventoryExtMapper wmsInventoryExtMapper;

    @Autowired
    private WmsInventoryLocationMapper wmsInventoryLocationMapper;

    @Autowired
    private WmsInboundOrderMapper wmsInboundOrderMapper;

    @Autowired
    private WmsInboundAllocationMapper wmsInboundAllocationMapper;

    @Autowired
    private WmsMailConfigExtMapper wmsMailConfigExtMapper;

    @Autowired
    private WmsInventoryLocationExtMapper wmsInventoryLocationExtMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private WmsShipmentPlanService wmsShipmentPlanService;//发运计划service

    @Autowired
    private WmsInboundRepairService wmsInboundRepairService;//维修service

    @Autowired
    private WmsBorrowCarService wmsBorrowCarService;//还车service


    @Autowired
    private WmsDealerCarBackService wmsDealerCarBackService;//退车service

    @Autowired
    private WmsInboundOrderDetailExtMapper wmsInboundOrderDetailExtMapper;
    @Autowired
    private WmsAsnTempExpandMapper wmsAsnTempExpandMapper;
    @Autowired
    private WmsMailLogMapper wmsMailLogMapper;

    private WmsShipmentPlanMapper wmsShipmentPlanMapper;

    @Autowired
    public void setWmsShipmentPlanMapper(WmsShipmentPlanMapper wmsShipmentPlanMapper) {
        this.wmsShipmentPlanMapper = wmsShipmentPlanMapper;
    }


    // 入库确认定时调度时间
    @Value("${wms.inbound.do.time}")
    private Integer WMS_INBOUND_DO_TIME;


    /**
     * 查询入库作业管理
     *
     * @param wmsAsnOrderQueryDTO 参数封装
     * @return 返回值
     * @throws IllegalAccessException 异常
     */
    @Override
    public Map<String, Object> getListAsnOrderBO(WmsAsnOrderQueryDTO wmsAsnOrderQueryDTO) throws Exception {
        logger.info("AsnOrderServiceImpl.getListAsnOrderBO param:{}", JSONObject.toJSONString(wmsAsnOrderQueryDTO));
        if (Objects.equals(wmsAsnOrderQueryDTO, null)) {
            logger.error("AsnOrderServiceImpl.getListAsnOrderBO pageVo must not be null");
            throw new IllegalArgumentException("分页参数不能为空");
        }
        String odWhCode = wmsAsnOrderQueryDTO.getOdWhCode();
        Map<String, Object> resultMap = Maps.newHashMap();
        //按照whcode 区分君马和重庆库业务；
        if (StringUtils.isNotBlank(odWhCode)) {
            if (WhCodeEnum.JM_CS.getValue().equals(odWhCode) ||
                    WhCodeEnum.JM_XY.getValue().equals(odWhCode)) {
                //君马库:
                resultMap = getWmsInboundorderListForJM(wmsAsnOrderQueryDTO);

            } else if (WhCodeEnum.UNLCN_XN_CQ.getValue().equals(odWhCode)) {
                //重庆库:
                resultMap = getWmsInboundorderListForCQ(wmsAsnOrderQueryDTO);
            } else {
                throw new BusinessException("该仓库不支持该操作!");
            }
        } else {
            throw new BusinessException("未查询到仓库的code信息");
        }
        return resultMap;

    }

    /**
     * 重庆库--入库记录查询列表
     * <p>
     * 2018-1-11 取消入库新功能 调整入库记录查询
     * </p>
     *
     * @param wmsAsnOrderQueryDTO 参数封装
     * @return 返回值
     * @throws IllegalAccessException 异常
     */
    private Map<String, Object> getWmsInboundorderListForCQ(WmsAsnOrderQueryDTO wmsAsnOrderQueryDTO) throws Exception {
        logger.info("AsnOrderServiceImpl.getWmsInboundorderListForCQ param:{}", JSONObject.toJSONString(wmsAsnOrderQueryDTO));
        if (Objects.equals(wmsAsnOrderQueryDTO, null)) {
            logger.error("AsnOrderServiceImpl.wmsInboundOrderBO pageVo must not be null");
            throw new BusinessException("参数不能为空");
        }
        Map<String, Object> resultMap = Maps.newHashMap();
        wmsAsnOrderQueryDTO.setLimitStart(wmsAsnOrderQueryDTO.getStartIndex());
        wmsAsnOrderQueryDTO.setLimitEnd(wmsAsnOrderQueryDTO.getPageSize());
        Map<String, Object> paramMap = ObjectToMapUtils.objectToMap(wmsAsnOrderQueryDTO);
        List<AsnOrderDTO> infos = wmsInboundAsnOrderAddMapper.queryForList(paramMap);
        List<WmsInboundOrderDTO> dtoList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(infos)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            infos.forEach((AsnOrderDTO v) -> {
                WmsInboundOrderDTO dto = new WmsInboundOrderDTO();
                BeanUtils.copyProperties(v, dto);
                dto.setOdWhName(v.getOdWhName());//设置仓库名
                dto.setGmtCreate(v.getGmtCreate() != null ? sdf.format(v.getGmtCreate()) : "");//入库时间
                dto.setGmtUpdate(v.getGmtUpdate() != null ? sdf.format(v.getGmtUpdate()) : "");
                BeanUtils.copyProperties(v.getAsnOrderDetailDTOList().get(0), dto);
                //查移库司机
                String driverId = v.getOdSupplierId();
                if (StringUtils.isNotBlank(driverId) && StringUtils.isNumeric(driverId)) {
                    //查询对应移库司机的信息；
                    SysUser sysUser = sysUserMapper.selectByPrimaryKey(Integer.parseInt(driverId));
                    if (!Objects.equals(sysUser, null)) {
                        dto.setDriverName(sysUser.getName());
                        dto.setDriverId(driverId);
                    }
                }
                dtoList.add(dto);
            });
            //resultMap.put("asnOrderList", bos);
            resultMap.put("asnOrderList", dtoList);
        }
        wmsAsnOrderQueryDTO.setPageNo(wmsAsnOrderQueryDTO.getStartIndex());
        wmsAsnOrderQueryDTO.setPageSize(wmsAsnOrderQueryDTO.getPageSize());
        wmsAsnOrderQueryDTO.setTotalRecord(wmsInboundAsnOrderAddMapper.queryForCount(paramMap));
        resultMap.put("wmsInboundOrderBO", wmsAsnOrderQueryDTO);
        return resultMap;
    }


    /**
     * 君马库--入库作业管理列表查询
     *
     * @param wmsAsnOrderQueryDTO 参数封装
     * @return 返回
     * @throws IllegalAccessException 异常抛出
     */
    private Map<String, Object> getWmsInboundorderListForJM(WmsAsnOrderQueryDTO wmsAsnOrderQueryDTO) throws IllegalAccessException {
        Map<String, Object> resultMap = Maps.newHashMap();
        wmsAsnOrderQueryDTO.setLimitStart(wmsAsnOrderQueryDTO.getStartIndex());
        wmsAsnOrderQueryDTO.setLimitEnd(wmsAsnOrderQueryDTO.getPageSize());
        Map<String, Object> paramMap = ObjectToMapUtils.objectToMap(wmsAsnOrderQueryDTO);
        logger.info("AsnOrderServiceImpl.wmsInboundOrderBO paramMap: {}", paramMap);
        List<AsnOrderDTO> infos = wmsInboundAsnOrderAddMapper.queryForList(paramMap);
        List<WmsInboundOrderDTO> dtoList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(infos)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            infos.forEach((AsnOrderDTO v) -> {
                WmsInboundOrderDTO dto = new WmsInboundOrderDTO();
                BeanUtils.copyProperties(v, dto);
                dto.setOdWhName(v.getOdWhName());//设置仓库名
                dto.setGmtCreate(v.getGmtCreate() != null ? sdf.format(v.getGmtCreate()) : "");//入库时间
                dto.setGmtUpdate(v.getGmtUpdate() != null ? sdf.format(v.getGmtUpdate()) : "");
                BeanUtils.copyProperties(v.getAsnOrderDetailDTOList().get(0), dto);
                //查移库司机
                String driverId = v.getOdSupplierId();
                if (StringUtils.isNotBlank(driverId) && StringUtils.isNumeric(driverId)) {
                    //查询对应移库司机的信息；
                    SysUser sysUser = sysUserMapper.selectByPrimaryKey(Integer.parseInt(driverId));
                    if (!Objects.equals(sysUser, null)) {
                        dto.setDriverId(driverId);
                        dto.setDriverName(sysUser.getName());
                    }
                }
                //根据入库类型查询设置发货(收货)仓库
                try {
                    setOtherInfoByBusinessType(dto);
                } catch (Exception e) {
                    throw new BusinessException("查询收发货仓库错误");
                }
                dtoList.add(dto);
            });
            //resultMap.put("asnOrderList", bos);
            resultMap.put("asnOrderList", dtoList);
        }
        wmsAsnOrderQueryDTO.setPageNo(wmsAsnOrderQueryDTO.getStartIndex());
        wmsAsnOrderQueryDTO.setPageSize(wmsAsnOrderQueryDTO.getPageSize());
        wmsAsnOrderQueryDTO.setTotalRecord(wmsInboundAsnOrderAddMapper.queryForCount(paramMap));
        resultMap.put("wmsInboundOrderBO", wmsAsnOrderQueryDTO);
        return resultMap;
    }

    /**
     * 设置根据入库类型设置其他信息
     *
     * @param dto
     */
    private void setOtherInfoByBusinessType(WmsInboundOrderDTO dto) throws Exception {

        if (StringUtils.isNotBlank(dto.getOdBusinessType())) {
            //PDI - 不变(没有发货, 只有收货仓库)
            if (InboundOrderBusinessTypeEnum.Z1.getCode().equals(dto.getOdBusinessType())) {
                dto.setDeliverWarehouse(dto.getOdWhName());
            }
            if (StringUtils.isNotBlank(dto.getOddVin())) {

                //调拨 - 根据车架号查询发运计划
                if (InboundOrderBusinessTypeEnum.Z2.getCode().equals(dto.getOdBusinessType())) {
                    WmsShipmentPlan wmsShipmentPlan = wmsShipmentPlanService.getShipmentPlanByVin(dto.getOddVin());
                    if (wmsShipmentPlan != null) {
                        dto.setShipWarehouse(wmsShipmentPlan.getSpDeliverWarehouseName());//发货仓库
                        dto.setDeliverWarehouse(wmsShipmentPlan.getSpDealerName());//经销商(收货)名称
                        dto.setCarrier(wmsShipmentPlan.getSpCarrier());//承运商
                        dto.setLogiContact(wmsShipmentPlan.getSpLogiContact());//承运商联系人
                        dto.setLogiPhone(wmsShipmentPlan.getSpLogiPhone());//承运商联系手机
                    }
                }
                //维修
                if (InboundOrderBusinessTypeEnum.Z4.getCode().equals(dto.getOdBusinessType())) {
                    WmsInboundRepair repair = wmsInboundRepairService.getWmsInboundRepairByVin(dto.getOddVin());
                    if (repair != null) {
                        dto.setDeliverWarehouse(repair.getRpWhName());
                    }
                }
                //还车
                if (InboundOrderBusinessTypeEnum.Z8.getCode().equals(dto.getOdBusinessType())) {
                    WmsBorrowCarDetail borrowCarDetail = wmsBorrowCarService.getBorrowCarDetailByVin(dto.getOddVin());
                    if (borrowCarDetail != null) {
                        WhCodeEnum codeEnum = WhCodeEnum.getByValue(borrowCarDetail.getBdWhcode());
                        if (codeEnum != null) {
                            dto.setDeliverWarehouse(codeEnum.getText());
                        }
                    }
                }
                //退车
                if (InboundOrderBusinessTypeEnum.Z9.getCode().equals(dto.getOdBusinessType())) {
                    WmsDealerCarBack dealerCarBack = wmsDealerCarBackService.getWmsDealerCarBackByVin(dto.getOddVin());
                    if (dealerCarBack != null) {
                        dto.setDeliverWarehouse(dealerCarBack.getCbWhName());
                        dto.setDealerName(dealerCarBack.getCbDealerName());//经销商
                    }
                }
            }
        }
    }

    @Override
    public boolean saveAsnOrder(WmsInboundOrderBO wmsInboundOrderBO) {
        WmsInboundOrder wmsInboundAsnOrder = new WmsInboundOrder();
        WmsInboundOrderDetail wmsInboundAsnOrderDetail = new WmsInboundOrderDetail();
        BeanUtils.copyProperties(wmsInboundOrderBO, wmsInboundAsnOrder);
        BeanUtils.copyProperties(wmsInboundOrderBO, wmsInboundAsnOrderDetail);
        //新建主表信息
        wmsInboundAsnOrder.setIsDeleted((byte) 0);
        wmsInboundAsnOrder.setOdStatus(String.valueOf(WmsStatusEnum.WMS_INBOUND_CREATE.getValue()));
        Long result = wmsInboundAsnOrderAddMapper.insertAsnOrderReturnId(wmsInboundAsnOrder);
        //新建从表信息
        wmsInboundAsnOrderDetail.setOddOdId(wmsInboundAsnOrder.getOdId());
        wmsInboundAsnOrderDetail.setIsDeleted((byte) 0);
        int resultD = wmsInboundAsnOrderDetailMapper.insert(wmsInboundAsnOrderDetail);
        return result > 0 && resultD > 0 ? true : false;
    }

    @Override
    public WmsInboundOrderBO getAsnOrderById(String odId) {
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("odId", odId);
        AsnOrderDTO asnOrderDTO = wmsInboundAsnOrderAddMapper.getAsnOrderById(paramMap);
        WmsInboundOrderBO wmsInboundOrderBO = new WmsInboundOrderBO();
        BeanUtils.copyProperties(asnOrderDTO, wmsInboundOrderBO);
        BeanUtils.copyProperties(asnOrderDTO.getAsnOrderDetailDTOList().get(0), wmsInboundOrderBO);
        return wmsInboundOrderBO;
    }

    @Override
    public void deleteAsnOrderByAsnOrderId(List<WmsInboundOrderBO> wmsInboundOrderBOList) {
        List<String> ids = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(wmsInboundOrderBOList)) {
            wmsInboundOrderBOList.stream().forEach(v -> {
                ids.add(String.valueOf(v.getOdId()));
            });
        }
        wmsInboundAsnOrderAddMapper.deleteByAsnOrderIds(ids);
        wmsInboundAsnOrderAddMapper.deleteDetailByAsnOrderIds(ids);
    }

    @Override
    public List<AsnOrderDTO> queryAsnOrderDetailListByAsnOrderId(List<WmsInboundOrderBO> asnOrderList) {
        Map<String, Object> paramMap = Maps.newHashMap();
        List asnOrderIds = Lists.newArrayList();
        for (WmsInboundOrderBO wmsInboundOrderBO : asnOrderList) {
            asnOrderIds.add(wmsInboundOrderBO.getOdId());
        }
        paramMap.put("asnOrderIds", asnOrderIds);
        List<AsnOrderDTO> asnOrderDTOList = wmsInboundAsnOrderAddMapper.queryAsnInfoByAsnIds(paramMap);
        return asnOrderDTOList;
    }

    @Override
    public void updateAsnOrderByAsnOrderId(List<WmsInboundOrderBO> idList, String asnStatus) {
        List<Long> ids = Lists.newArrayList();
        for (WmsInboundOrderBO wmsInboundOrderBO : idList) {
            ids.add(wmsInboundOrderBO.getOdId());
        }
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("ids", ids);
        paramMap.put("asnStatus", asnStatus);
        wmsInboundAsnOrderAddMapper.updateAsnOrderByAsnOrderId(paramMap);

    }

    @Override
    public boolean updateAsnOrderByEntity(WmsInboundOrderBO wmsInboundOrderBO) {
        WmsInboundOrder wmsInboundAsnOrder = new WmsInboundOrder();
        BeanUtils.copyProperties(wmsInboundOrderBO, wmsInboundAsnOrder);
        WmsInboundOrderExample example = new WmsInboundOrderExample();
        example.createCriteria().andOdIdEqualTo(wmsInboundOrderBO.getOdId());

        WmsInboundOrderDetail wmsInboundAsnOrderDetail = new WmsInboundOrderDetail();
        BeanUtils.copyProperties(wmsInboundOrderBO, wmsInboundAsnOrderDetail);
        WmsInboundOrderDetailExample detailExample = new WmsInboundOrderDetailExample();
        detailExample.createCriteria().andOddOdIdEqualTo(wmsInboundOrderBO.getOdId());

        int result = wmsInboundAsnOrderMapper.updateByExampleSelective(wmsInboundAsnOrder, example);

        int result2 = wmsInboundAsnOrderDetailMapper.updateByExampleSelective(wmsInboundAsnOrderDetail, detailExample);

        return (result > 0 && result2 > 0);
    }

    /**
     * 入库确认--重庆库
     *
     * @param wmsInboundAllocationBO 参数封装
     * @param userId                 用户id
     * @throws Exception 异常
     */
    @Override
    public void updateConfirmInbound(WmsInboundAllocationBO wmsInboundAllocationBO, String userId) throws Exception {
        logger.info("AsnOrderServiceImpl.updateConfirmInbound param{}", JSONObject.toJSONString(wmsInboundAllocationBO));
        if (StringUtils.isBlank(userId)) {
            throw new BusinessException("用户Id不能为空!");
        }
        WmsInboundOrder wmsInboundOrder = wmsInboundOrderMapper.selectByPrimaryKey(Long.valueOf(wmsInboundAllocationBO.getAlOdId()));
        if (Objects.equals(Integer.valueOf(wmsInboundOrder.getOdStatus()), WmsInboundStatusEnum.WMS_INBOUND_FINISH.getValue())) {
            throw new BusinessException("该订单已经入库,无需重复操作!");
        }
        if (Objects.equals(Integer.valueOf(wmsInboundOrder.getOdStatus()), WmsInboundStatusEnum.WMS_INBOUND_CREATE.getValue())) {
            throw new BusinessException("该订单还未进行收货质检!");
        }
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(Integer.parseInt(userId));
        String orderStatus = String.valueOf(WmsInboundStatusEnum.WMS_INBOUND_FINISH.getValue());
        //修改订单状态
        List<InboundToTms> msgList = Lists.newArrayList();
        try {
            List<Long> ids = Lists.newArrayList();
            ids.add(Long.valueOf(wmsInboundAllocationBO.getAlOdId()));
            Map<String, Object> paramMap = Maps.newHashMap();
            paramMap.put("ids", ids);
            paramMap.put("odStatus", orderStatus);
            paramMap.put("inboundConfirmId", sysUser.getId());
            wmsInboundAsnOrderAddMapper.updateAsnOrderByAsnOrderId(paramMap);

            //修改分配表状态
            //for(WmsInboundOrderBO wmsInboundOrderBO : wmsInboundOrderBOList){
            Map<String, Object> alParamMap = Maps.newHashMap();
            alParamMap.put("alStatus", WmsInboundAllocationStatusEnum.INBOUND_STATUS.getValue());
            alParamMap.put("alOdId", wmsInboundAllocationBO.getAlOdId());
            wmsAllocationExtMapper.updateStatusByAsnOrderId(alParamMap);
            //
            // 货物底盘号                       vin
            // 客户运单号                       custshipno
            // 入库时间,yyyy-MM-dd hh24:mi:ss  dt_inware
            // 入库操作人                      userno
            // 入库仓库                        warehouse
            // 库位                           pos
            // 入库类型，1.正常入库 ；2.异常入库   type
            //
            Map<String, Object> map = Maps.newHashMap();
            map.put("odId", wmsInboundAllocationBO.getAlOdId());
            AsnOrderDTO asnOrderDTO = wmsInboundAsnOrderAddMapper.getAsnOrderById(map);
            if (asnOrderDTO != null) {
                // 生成库存
                WmsInventory wmsInventory = new WmsInventory();
                wmsInventory.setInvVehicleBrandName(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddVehicleBrandCode());
                wmsInventory.setInvVehicleBrandCode(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddVehicleBrandName());
                wmsInventory.setInvVehicleSeriesCode(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddVehicleSeriesCode());
                wmsInventory.setInvVehicleSeriesCode(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddVehicleSeriesName());
                wmsInventory.setInvVehicleSpecCode(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddVehicleSpecCode());
                wmsInventory.setInvVehicleSpecName(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddVehicleSpecName());
                wmsInventory.setInvVehicleSpecDesc(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddVehicleSpecDesc());
                wmsInventory.setInvCustomerName(asnOrderDTO.getOdCustomerName());//货主名称
                wmsInventory.setInvWhCode(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhCode());
                wmsInventory.setInvWhName(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhName());
                wmsInventory.setInvMaterialCode(StringUtils.isNotBlank(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddMaterialCode()) ?
                        asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddMaterialCode() : "");//增加库存的物料编码
                wmsInventory.setInvMaterialName(StringUtils.isNotBlank(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddMaterialName()) ?
                        asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddMaterialName() : "");//增加库存的物料名称
                wmsInventory.setIsDeleted((byte) 1);
                wmsInventory.setGmtCreate(new Date());
                wmsInventory.setGmtUpdate(new Date());
                wmsInventoryExtMapper.insertInventory(wmsInventory);
                Long invId = wmsInventory.getInvId();

                //新增库存商品所在的库位信息
                WmsInventoryLocation wmsInventoryLocation = new WmsInventoryLocation();
                wmsInventoryLocation.setInvlocInvId(invId);
                wmsInventoryLocation.setInvlocCustomerCode(String.valueOf(asnOrderDTO.getOdCustomerCode() == null ? "" : asnOrderDTO.getOdCustomerCode()));
                wmsInventoryLocation.setInvlocCustomerName(asnOrderDTO.getOdCustomerName() == null ? "" : asnOrderDTO.getOdCustomerName());
                wmsInventoryLocation.setInvlocVin(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddVin());
                wmsInventoryLocation.setInvlocWaybillNo(asnOrderDTO.getOdWaybillNo());
                wmsInventoryLocation.setInvlocWhCode(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhCode());
                wmsInventoryLocation.setInvlocWhName(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhName());
                wmsInventoryLocation.setInvlocOdId(asnOrderDTO.getOdId());//订单ID
                wmsInventoryLocation.setInvlocZoneCode(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhZoneCode());//库区code
                wmsInventoryLocation.setInvlocZoneName(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhZoneCode());//库区
                wmsInventoryLocation.setInvlocLocCode(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhLocCode());//库位code
                wmsInventoryLocation.setInvlocLocName(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhLocCode());//库位
                wmsInventoryLocation.setIsDeleted((byte) 1);
                wmsInventoryLocation.setGmtCreate(new Date());
                wmsInventoryLocation.setGmtUpdate(new Date());
                wmsInventoryLocationMapper.insert(wmsInventoryLocation);

                //更新inboundallocation 表中的入库状态
                WmsInboundAllocationExample allocationExample = new WmsInboundAllocationExample();
                WmsInboundAllocationExample.Criteria criteria = allocationExample.createCriteria();
                criteria.andAlVinEqualTo(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddVin());
                criteria.andIsDeletedNotEqualTo(DeleteFlagEnum.DELETED.getValue());
                List<WmsInboundAllocation> wmsInboundAllocations = wmsInboundAllocationMapper.selectByExample(allocationExample);
                if (CollectionUtils.isNotEmpty(wmsInboundAllocations)) {
                    WmsInboundAllocation wmsInboundAllocation = wmsInboundAllocations.get(0);
                    wmsInboundAllocation.setIsDeleted(DeleteFlagEnum.NORMAL.getValue());
                    wmsInboundAllocation.setGmtUpdate(new Date());
                    wmsInboundAllocation.setAlStatus(WmsInboundAllocationStatusEnum.INBOUND_STATUS.getValue());
                    wmsInboundAllocation.setModifyUserName(sysUser.getName());
                    wmsInboundAllocation.setModifyUserId(String.valueOf(sysUser.getId()));
                    wmsInboundAllocationMapper.updateByPrimaryKeySelective(wmsInboundAllocation);
                }
                //推送已入库状态到app--重庆库
                String jsonStr = "{ \"locName\": " + asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhLocCode() + ", \"status\":\"30\", \"statusName\": \"已入库\" }";
                JpushClientUtils.sendToAllAndroid(wmsInboundOrder.getOdSupplierId(), jsonStr, TYPE_INBOUND);
            }
        } catch (BusinessException ex) {
            logger.error("AsnOrderServiceImpl.updateConfirmInbound BussinessException:", ex);
            throw new BusinessException(ex.getMessage());
        } catch (Exception e) {
            logger.error("AsnOrderServiceImpl.updateConfirmInbound error:", e);
            throw new BusinessException("入库异常");
        }
    }

    @Override
    public void confirmInboundMailTo(String vin) {
        // 获取入库订单详情
        List<InboundInfoDTO> inboundInfoList = wmsInboundOrderDetailExtMapper.inboundInfo(vin);
        if (CollectionUtils.isEmpty(inboundInfoList))
            return;
        InboundInfoDTO inboundInfo = inboundInfoList.get(0);

        // 入库时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String storageTime = (inboundInfo.getGmtCreate() == null) ? "" : sdf.format(inboundInfo.getGmtCreate());
        // 入库仓库
        String warehousingWarehouse = inboundInfo.getWarehousingWarehouse();
        // 入库人
        String storagePerson = inboundInfo.getStoragePerson();


        // 获取邮件配置信息
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("isDelete", 1);
        paramsMap.put("wmsMailType", 1);
        List<WmsMailConfig> mailConfigList = wmsMailConfigExtMapper.findParams(paramsMap);
        WmsMailConfig wmsMailConfig = mailConfigList.get(0);
        if (wmsMailConfig == null)
            return;

        // 邮件服务器
        String hostUrl = wmsMailConfig.getWmsHostUrl();
        // 用户名
        String user = wmsMailConfig.getWmsUserName();
        // 密码
        String pwd = wmsMailConfig.getWmsUserPwd();
        // 接收人
        String receipts = wmsMailConfig.getWmsReceipt();
        // 抄送人
        String ccs = wmsMailConfig.getWmsCc();
        // 邮件标题
        String title = wmsMailConfig.getWmsMailTitle();
        // 替换底盘号占位符
        title = title.replaceAll("::vin::", vin);
        // 邮件内容
        String content = wmsMailConfig.getWmsSendTemplate();
        // 替换标题占位符
        content = content.replaceAll("::title::", title);
        // 替换底盘号的占位符
        content = content.replaceAll("::vin::", vin);
        // 替换入库时间的占位符
        content = content.replaceAll("::storageTime::", storageTime);
        // 替换入库仓库的占位符
        content = content.replaceAll("::warehousingWarehouse::", warehousingWarehouse);
        // 替换入库人的占位符
        content = content.replaceAll("::storagePerson::", storagePerson);

        // 发送邮件
        SendMail.sendMailMess(hostUrl, user, pwd, title, content, receipts, ccs);
    }


    @Override
    public WmsInboundOrderBO queryByWaybillOrVin(String queryParam) {
        AsnOrderDTO asnOrderDTO = wmsInboundAsnOrderAddMapper.queryByWaybillOrVin(queryParam);

        if (null != asnOrderDTO && !Objects.isNull(asnOrderDTO)) {
            WmsInboundOrderBO wmsInboundOrderBO = new WmsInboundOrderBO();
            BeanUtils.copyProperties(asnOrderDTO, wmsInboundOrderBO);
            BeanUtils.copyProperties(asnOrderDTO.getAsnOrderDetailDTOList().get(0), wmsInboundOrderBO);
            return wmsInboundOrderBO;
        } else {
            return null;
        }

    }

    /**
     * 根据车架号查询订单
     *
     * @param oddVin
     * @return
     */
    @Override
    public WmsInboundOrderBO queryByVin(String oddVin) {
        AsnOrderDTO asnOrderDTO = wmsInboundAsnOrderAddMapper.queryByVin(oddVin);
        if (null != asnOrderDTO && !Objects.isNull(asnOrderDTO)) {
            WmsInboundOrderBO wmsInboundOrderBO = new WmsInboundOrderBO();
            BeanUtils.copyProperties(asnOrderDTO, wmsInboundOrderBO);
            BeanUtils.copyProperties(asnOrderDTO.getAsnOrderDetailDTOList().get(0), wmsInboundOrderBO);
            wmsInboundOrderBO.setOddWhLocName(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhLocCode());
            if (!Objects.equals(asnOrderDTO.getGmtCreate(), null)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                wmsInboundOrderBO.setGmtCreate(sdf.format(asnOrderDTO.getGmtCreate()));//设置入库时间
            }
            return wmsInboundOrderBO;
        } else {
            return null;
        }
    }


    /**
     * 钥匙匹配
     *
     * @param vin
     * @return
     * @throws Exception
     */
    @Override
    public WmsInboundOrderBO getKeysInfoByVin(String vin) throws Exception {
        logger.info("AsnOrderServiceImpl.getKeysInfoByVin param:{}", vin);
        AsnOrderDTO asnOrderDTO = wmsInboundAsnOrderAddMapper.queryByVinForKey(vin);
        if (null != asnOrderDTO && !Objects.isNull(asnOrderDTO)) {
            WmsInboundOrderBO wmsInboundOrderBO = new WmsInboundOrderBO();
            BeanUtils.copyProperties(asnOrderDTO, wmsInboundOrderBO);
            BeanUtils.copyProperties(asnOrderDTO.getAsnOrderDetailDTOList().get(0), wmsInboundOrderBO);
            wmsInboundOrderBO.setOddWhLocName(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhLocCode());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (!Objects.equals(asnOrderDTO.getGmtCreate(), null)) {
                wmsInboundOrderBO.setGmtCreate(sdf.format(asnOrderDTO.getGmtCreate()));//设置入库时间
            }
            return wmsInboundOrderBO;
        } else {
            return null;
        }
    }


    /**
     * <p>
     * 2018/1/8  新需求 --取消入库
     * 根据车架号,进行取消入库操作--需要同步tms
     * 防止入库邮件重复发送
     * </p>
     *
     * @param dto 参数对象
     * @return 返回值
     * @throws Exception 异常
     */
    @Override
    public void updateCancelInbound(WmsInboundOrderDTO dto) throws Exception {
        logger.info("AsnOrderServiceImpl.updateCancelInbound param:{}", JSONObject.toJSONString(dto));
        if (Objects.equals(dto, null))
            throw new BusinessException("传入参数不能为空!");
        if (StringUtils.isBlank(dto.getUserId()))
            throw new BusinessException("用户id不能为空!");
        if (StringUtils.isBlank(dto.getWhCode()))
            throw new BusinessException("仓库code不能为空!");
        if (dto.getOdId() == null)
            throw new BusinessException("传入的订单id为空!");
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(Integer.valueOf(dto.getUserId()));
        HashMap<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("odId", dto.getOdId());
        paramMap.put("notDel", DeleteFlagEnum.NORMAL.getValue());
        paramMap.put("orderBy", "a.od_id desc");
        paramMap.put("start", 0);
        paramMap.put("end", 1);
        List<AsnOrderDTO> asnOrderDTOS = wmsInboundOrderDetailExtMapper.selectOrderByParam(paramMap);
        if (CollectionUtils.isNotEmpty(asnOrderDTOS)) {
            //状态校验
            AsnOrderDTO asnOrderDTO = asnOrderDTOS.get(0);
            if (String.valueOf(WmsInboundStatusEnum.WMS_INBOUND_CANCLE.getValue()).equals(asnOrderDTO.getOdStatus())) {
                throw new BusinessException("该数据已经进行该操作,无需重复操作!");
            }
            if (!String.valueOf(WmsInboundStatusEnum.WMS_INBOUND_FINISH.getValue()).equals(asnOrderDTO.getOdStatus()))
                throw new BusinessException("该数据未进行入库确认操作,不能进行入库取消");
            if (CollectionUtils.isNotEmpty(asnOrderDTO.getAsnOrderDetailDTOList())) {
                AsnOrderDetailDTO detailDTO = asnOrderDTO.getAsnOrderDetailDTOList().get(0);
                if (detailDTO != null) {
                    WmsShipmentPlanExample planExample = new WmsShipmentPlanExample();
                    planExample.createCriteria().andSpVinEqualTo(detailDTO.getOddVin())
                            .andOldModifyTypeNotEqualTo(WmsShipmentPlanModifyTypeEnum.DELETE.getValue());
                    List<WmsShipmentPlan> wmsShipmentPlans = wmsShipmentPlanMapper.selectByExample(planExample);
                    if (CollectionUtils.isNotEmpty(wmsShipmentPlans)) {
                        throw new BusinessException("该数据已经创建发运记录,不支持该操作!");
                    }
                }
            }
            //更新库存表状态逻辑删除-不释放库位//更新order表的状态为取消入库状态//防止入库邮件重复发送
            paramMap.put("del", DeleteFlagEnum.DELETED.getValue());
            paramMap.put("cancelStatus", WmsInboundStatusEnum.WMS_INBOUND_CANCLE.getValue());
            if (sysUser != null) {
                paramMap.put("cancelUserId", sysUser.getId());
                paramMap.put("cancelUserName", sysUser.getName());
            }
            wmsInventoryLocationExtMapper.updateCancelStatusByParam(paramMap);
            //调用tms同步数据--取消入库
            try {
                String result = inboundCancelTms(asnOrderDTO, sysUser);
                if (StringUtils.isNotBlank(result)) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    Boolean success = jsonObject.getBoolean("success");
                    if (!success) {
                        String message = jsonObject.getString("message");
                        throw new BusinessException("同步TMS失败 error:", message);
                    }
                }
            } catch (BusinessException e) {
                logger.error("AsnOrderServiceImpl.updateCancelInbound 同步TMS接口失败 error:", e.getMessage());
                throw new BusinessException("TMS返回错误信息:" + e.getMessage());
            } catch (Exception e) {
                logger.error("AsnOrderServiceImpl.updateCancelInbound 同步TMS接口连接超时失败!");
                throw new BusinessException("同步TMS接口连接超时");
            }
        }
    }


    /**
     * 取消入库同步数据到tms
     *
     * @param asnOrderDTO 参数封装
     * @param sysUser     用户
     */
    private String inboundCancelTms(AsnOrderDTO asnOrderDTO, SysUser sysUser) {
        // 构建URL
        String url = propertyUrl;
        Integer time = Integer.parseInt(propertyTime);
        String encode_key = propertyKey;
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("encode-key", encode_key);
        url = url + "/mCancelInware.jspx";
        map.put("vin", asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddVin());
        map.put("custshipno", asnOrderDTO.getOdWaybillNo());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("dt_cancel", sdf.format(new Date()));
        map.put("userno", sysUser == null ? "" : sysUser.getName());
        map.put("warehouse", WhCodeEnum.UNLCN_XN_CQ.getText());
        map.put("pos", asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhLocCode());
        String result = null;
        try {
            result = HttpRequestUtil.sendHttpPost(url, headerMap, map, time);
        } catch (Exception e) {
            throw new BusinessException("访问tms接口失败");
        }
        return result;
    }

    /**
     * 查询入库记录功能
     * <p>
     * 2018-1-22 新需求 (君马库)入库记录查询页面增加“物料代码”、“物料名称”、“颜色代码”、“颜色”字段显示，导出的文件中也需要包含这四个字段；
     * <p>
     *
     * @param paramMap 参数封装map
     * @return 返回值
     */
    @Override
    public Map<String, Object> queryInboundRecord(Map<String, Object> paramMap) {
        logger.info("AsnOrderServiceImpl.queryInboundRecord param:{}", JSONObject.toJSONString(paramMap));
        Map<String, Object> resultMap = Maps.newHashMap();
        Integer pageNo = Integer.valueOf(paramMap.get("pageNo").toString());
        Integer pageSize = Integer.valueOf(paramMap.get("pageSize").toString());
        paramMap.put("limitStart", (pageNo - 1) * pageSize < 0 ? 0 : (pageNo - 1) * pageSize);
        paramMap.put("limitEnd", pageSize);
        //按照天数传入入库起止时间
        Object endDate = paramMap.get("rk_end_date");
        if (!Objects.equals(endDate, null)) {
            String rk_end_date = endDate.toString();
            if (StringUtils.isNotBlank(rk_end_date)) {
                paramMap.put("rk_end_date", rk_end_date + " 23:59:59");
            }
        }
        Object startDate = paramMap.get("rk_start_date");
        if (!Objects.equals(startDate, null)) {
            String rk_start_date = startDate.toString();
            if (StringUtils.isNotBlank(rk_start_date)) {
                paramMap.put("rk_start_date", rk_start_date + " 00:00:00");
            }
        }
        paramMap.put("orderByClause", "rkDate desc");
        String odWhCode = paramMap.get("odWhCode").toString();
        //2018-1-11 因重庆库增加的取消入库和退库业务 查询入库记录列表调整
        if (WhCodeEnum.UNLCN_XN_CQ.getValue().equals(odWhCode)) {
            //配置系统变量修复sql报错
            wmsInboundAsnOrderAddMapper.updateSetSQLMode();
            List<Map<String, Object>> infos = wmsInboundAsnOrderAddMapper.queryinboundListForCQ(paramMap);
            resultMap.put("inboundRecord", infos);
            paramMap.put("totalRecord", wmsInboundAsnOrderAddMapper.queryinboundCountForCQ(paramMap));
            resultMap.put("wmsInboundRecordBO", paramMap);
        }

        if (WhCodeEnum.JM_CS.getValue().equals(odWhCode) ||
                WhCodeEnum.JM_XY.getValue().equals(odWhCode)) {
            List<Map<String, Object>> infos = wmsInboundAsnOrderAddMapper.queryInboundListForJm(paramMap);
            resultMap.put("inboundRecord", infos);
            paramMap.put("totalRecord", wmsInboundAsnOrderAddMapper.queryinboundCountForJm(paramMap));
            resultMap.put("wmsInboundRecordBO", paramMap);
        }
        return resultMap;
    }

    @Autowired
    private WmsWarehouseNoticeExtMapper wmsWarehouseNoticeExtMapper;

    /**
     * 获取车型
     * <p>
     * 2018-4-23 此方法入库通知单重构重写
     * </p>
     *
     * @return
     */
    @Override
    public List<WmsWarehouseNoticeDetail> getVehicleSpec(String whCode) {
        if (logger.isInfoEnabled()) {
            logger.info("AsnOrderServiceImpl.getVehicleSpec params:{}", whCode);
        }
        if (StringUtils.isBlank(whCode)) {
            throw new BusinessException("仓库code不能为空!");
        }
        HashMap<String, Object> params = Maps.newHashMap();
        params.put("notDel", DeleteFlagEnum.NORMAL.getValue());
        params.put("whCode", whCode);
        return wmsWarehouseNoticeExtMapper.selectAllNoticeVehicleSpecListByParam(params);
    }

    /**
     * 获取车型
     * <p>
     * 2018-4-23 此方法过时,新方法{@link AsnOrderServiceImpl#getVehicleSpec}
     * </p>
     *
     * @return
     */
    @Override
    @Deprecated
    public List<VehicleSpecBO> getVehicleSpecOld(String whCode) {
        WmsInboundOrderDetailExample example = new WmsInboundOrderDetailExample();
        example.createCriteria().andOddWhCodeEqualTo(whCode);
        List<WmsInboundOrderDetail> wmsInboundOrderDetailList = wmsInboundAsnOrderDetailMapper.selectByExample(example);
        List<VehicleSpecBO> vehicleSpecBOList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(wmsInboundOrderDetailList) && wmsInboundOrderDetailList.size() > 0) {
            wmsInboundOrderDetailList.forEach(wmsInboundOrderDetail -> {
                VehicleSpecBO vehicleSpecBO = new VehicleSpecBO();
                vehicleSpecBO.setCode(wmsInboundOrderDetail.getOddVehicleSpecCode());
                vehicleSpecBO.setName(wmsInboundOrderDetail.getOddVehicleSpecName());
                if (!Objects.equals(vehicleSpecBO.getCode(), null) || !Objects.equals(vehicleSpecBO.getName(), null)) {
                    if (!vehicleSpecBOList.contains(vehicleSpecBO)) {
                        vehicleSpecBOList.add(vehicleSpecBO);
                    }
                }
            });
        }
        return vehicleSpecBOList;
    }

    /**
     * 收货入库 - 君马
     *
     * @param wmsInboundOrderBO
     * @throws Exception
     */
    @Override
    public void updateToInConfirm(WmsInboundOrderBO wmsInboundOrderBO) throws Exception {
        logger.info("AsnOrderServiceImpl.updateToInConfirm param: {}", wmsInboundOrderBO);
        if (wmsInboundOrderBO == null || wmsInboundOrderBO.getOdId() == null) {
            throw new BusinessException("参数为空");
        }
        if (StringUtils.isBlank(wmsInboundOrderBO.getOdCheckResult())) {
            throw new BusinessException("检验结果为空");
        }
        WmsInboundOrder updateOrder = new WmsInboundOrder();
        updateOrder.setOdId(wmsInboundOrderBO.getOdId());
        updateOrder.setOdInCheckDesc(wmsInboundOrderBO.getOdCheckDesc());
        updateOrder.setOdInCheckResult(wmsInboundOrderBO.getOdCheckResult());
        wmsInboundOrderMapper.updateByPrimaryKeySelective(updateOrder);
    }

    /**
     * 根据车架号获取数据
     *
     * @param vin
     * @return
     * @throws Exception
     */
    @Override
    public WmsInboundOrderDTO getInBoundInfoByVin(String vin) throws Exception {

        AsnOrderDTO asnOrderDTO = wmsInboundAsnOrderAddMapper.queryByVin(vin);
        if (null != asnOrderDTO && !Objects.isNull(asnOrderDTO)) {
            WmsInboundOrderDTO inboundOrderDTO = new WmsInboundOrderDTO();
            BeanUtils.copyProperties(asnOrderDTO, inboundOrderDTO);
            BeanUtils.copyProperties(asnOrderDTO.getAsnOrderDetailDTOList().get(0), inboundOrderDTO);
            if (!Objects.equals(asnOrderDTO.getGmtCreate(), null)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                inboundOrderDTO.setGmtCreate(sdf.format(asnOrderDTO.getGmtCreate()));//设置入库时间
            }
            setOtherInfoByBusinessType(inboundOrderDTO);
            return inboundOrderDTO;
        }
        return null;
    }

    @Override
    public WmsInboundOrderDTO updateToInConfirm2(String vin) throws Exception {
        AsnOrderDTO asnOrderDTO = null;
        if (vin.length() == 17) {
            asnOrderDTO = wmsInboundAsnOrderAddMapper.queryByVin(vin);
        } else {
            asnOrderDTO = wmsInboundAsnOrderAddMapper.queryByDriverId(Long.valueOf(vin));
        }
        if (asnOrderDTO == null)
            return null;
        if (null != asnOrderDTO && !Objects.isNull(asnOrderDTO)) {
            WmsInboundOrderDTO inboundOrderDTO = new WmsInboundOrderDTO();
            BeanUtils.copyProperties(asnOrderDTO, inboundOrderDTO);
            BeanUtils.copyProperties(asnOrderDTO.getAsnOrderDetailDTOList().get(0), inboundOrderDTO);
            if (!Objects.equals(asnOrderDTO.getGmtCreate(), null)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                inboundOrderDTO.setGmtCreate(sdf.format(asnOrderDTO.getGmtCreate()));//设置入库时间
            }
            setOtherInfoByBusinessType(inboundOrderDTO);

            WmsInboundOrder updateOrder = new WmsInboundOrder();
            updateOrder.setOdId(inboundOrderDTO.getOdId());
            updateOrder.setOdInCheckDesc(inboundOrderDTO.getOdCheckDesc());
            updateOrder.setOdInCheckResult(inboundOrderDTO.getOdCheckResult());
            wmsInboundOrderMapper.updateByPrimaryKeySelective(updateOrder);

            return inboundOrderDTO;
        }
        return null;
    }


    /**
     * 入库邮件发送
     */
    public void getInboundSendMailData() {
        logger.info("AsnOrderServiceImpl.getInboundSendMailData param {}");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat format3 = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        try {

//            String startTime = null;
//            String endTime = null;
//
//            // 判断当前时间是在十二点内 还是  五点内  还是 二十三点内
//            String time = format.format(new Date());
//            String house = time.substring(time.indexOf(" ")+1, time.indexOf(" ")+3);
//            switch (house) {
//                case "12":
//                {
//                    // 开始时间
//                    Calendar currCalendar = new GregorianCalendar();
//                    currCalendar.set(Calendar.HOUR_OF_DAY, 0);
//                    currCalendar.set(Calendar.MINUTE, 0);
//                    currCalendar.set(Calendar.SECOND, 0);
//                    startTime = format.format(currCalendar.getTime());
//                }
//                break;
//                case "16":
//                {
//                    // 开始时间
//                    Calendar calendar = Calendar.getInstance();
//                    calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) -270);
//                    startTime = format.format(calendar.getTime());
//                }
//                break;
//                case "23":
//                {
//                    // 开始时间
//                    Calendar calendar = Calendar.getInstance();
//                    calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) -440);
//                    startTime = format.format(calendar.getTime());
//                }
//            }
//            // 截至时间
//            endTime = format.format(new Date());
//            List<InboundExcelDTO> inboundExcelList = wmsInventoryLocationExtMapper.inboundExcelData(startTime, endTime, "UNLCN_XN_CQ");
//            logger.info("起始时间：" + startTime);
//            logger.info("创建时间：" + endTime);
//            logger.info("入库的车辆数：" + inboundExcelList.size());
//            if (org.springframework.util.CollectionUtils.isEmpty(inboundExcelList))
//                return;

            // 查询当天所有入库的车辆
            Calendar currCalendar = new GregorianCalendar();
            currCalendar.set(Calendar.HOUR_OF_DAY, 0);
            currCalendar.set(Calendar.MINUTE, 0);
            currCalendar.set(Calendar.SECOND, 0);
            String startTime = format.format(currCalendar.getTime());// 起始时间
            Date endDate = new Date();
            String endTime = format.format(endDate);
            String normalCode = WmsInboundOrderStockTransferEnum.STOCK_NORMAL.getCode();
            //邮件数据参数封装
            HashMap<String, Object> paramMap = Maps.newHashMap();
            paramMap.put("startTime", startTime);
            paramMap.put("endTime", endTime);
            paramMap.put("invlocWhCode", WhCodeEnum.UNLCN_XN_CQ.getValue());
            paramMap.put("normal", normalCode);
            paramMap.put("notSend", InventoryLocationStatusEnum.MAI_NOT_SEND.getCode());
            List<InboundExcelDTO> inboundExcelList = wmsInventoryLocationExtMapper.inboundExcelDataNew(paramMap);
            //List<InboundExcelDTO> inboundExcelList = wmsInventoryLocationExtMapper.inboundExcelData(startTime, endTime, whcode, normalCode);
            logger.info("起始时间：" + startTime);
            logger.info("创建时间：" + endTime);
            logger.info("当天所有入库的车辆数：" + inboundExcelList.size());
            if (CollectionUtils.isEmpty(inboundExcelList))
                return;
            int no = 1;
            for (InboundExcelDTO inboundExcelDTO : inboundExcelList) {
                inboundExcelDTO.setNo(no);
                Date gmtCreate = inboundExcelDTO.getGmtCreate();
                if (gmtCreate != null) {
                    String[] gmtCreates = format.format(gmtCreate).split(" ");
                    inboundExcelDTO.setDate(gmtCreates[0]);
                    inboundExcelDTO.setInboundDate(gmtCreates[1]);
                }
                no++;
            }

            // 获取当天生成的所有xls文件名称
            String filePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
            filePath = filePath + "inboundxls/";
            File directory = new File(filePath);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            //清除老的文件
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endDate);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            //23：50  运行一次,用小时去删除旧文件
            if (hour == 23) {
                // 删除昨天的所有文件
                File[] files = new File(filePath).listFiles();
                if (files != null && files.length > 0) {
                    for (File file : files) {
                        String fileName = file.getName();
                        file.delete();
                    }
                }
            }
            // 获取目录下的所有文件名称
            List<String> nameList = getFileName(filePath);

            // 累加当天生成的所有xls
            String current = format2.format(endDate);
            if (CollectionUtils.isEmpty(nameList)) {
                // 如果当天没有生成xls，则从一往上累加
                filePath = filePath + current + "-1" + ".xls";
            } else {
                // 从一开始往上累加
                Integer[] nums = new Integer[nameList.size()];
                for (int i = 0; nameList.size() > i; i++) {
                    String name = nameList.get(i);
                    if (name.contains("-")) {
                        Integer num = Integer.valueOf(name.substring(name.lastIndexOf("-") + 1, name.indexOf(".")));
                        nums[i] = num;
                    } else {
                        nums[i] = 0;
                    }
                }
                Arrays.sort(nums);
                int maxNum = 0;
                if (nums.length != 0) {
                    maxNum = nums[nums.length - 1];
                }
                filePath = filePath + current + "-" + String.valueOf(maxNum + 1) + ".xls";
            }

            // 生成入库车辆的xls文件
            InboundExcelUtils.export(inboundExcelList, filePath);

            // 获取邮件配置信息
            Map<String, Object> paramsMap = new HashMap<String, Object>();
            paramsMap.put("isDelete", 1);
            paramsMap.put("wmsMailType", 1);
            List<WmsMailConfig> mailConfigList = wmsMailConfigExtMapper.findParams(paramsMap);
            WmsMailConfig wmsMailConfig = mailConfigList.get(0);
            if (wmsMailConfig == null)
                return;

            // 邮件服务器
            String hostUrl = wmsMailConfig.getWmsHostUrl();
            // 用户名
            String user = wmsMailConfig.getWmsUserName();
            // 密码
            String pwd = wmsMailConfig.getWmsUserPwd();
            // 接收人
            String receipts = wmsMailConfig.getWmsReceipt();
            logger.info("邮件接收人：" + receipts);
            if (StringUtil.isEmpty(receipts)) {
                return;
            }
            // 抄送人
            String ccs = wmsMailConfig.getWmsCc();

            // 邮件标题
            String title = "您好,请查收截至" + format3.format(endDate) + "入库记录";
            // 邮件内容
            String content = "您好,请查收截至" + format3.format(endDate) + "入库记录";
            // 发送邮件通知
            SendMail.sendMailHaveFile(hostUrl, user, pwd, title, content, receipts, ccs, filePath);
            //记录日志
            Runnable mailLog = () -> {
                WmsMailLog wmsMailLog = new WmsMailLog();
                wmsMailLog.setGmtCreate(new Date());
                wmsMailLog.setMailContent(new Gson().toJson(inboundExcelList));
                wmsMailLog.setReceiver(receipts);
                wmsMailLog.setSendType(WmsGateControllerTypeEnum.GATE_IN.getCode());
                wmsMailLogMapper.insertSelective(wmsMailLog);
                //更新order表的邮件发送状态为已发送
                wmsInboundOrderDetailExtMapper.updateOrderSendFlagBatch(inboundExcelList);
            };
            new Thread(mailLog).start();

        } catch (Exception e) {
            logger.error("AsnOrderServiceImpl.inboundSendMailData error: {}", e);
        }
    }

    /**
     * 颜色下拉列表
     * <p>
     * 2018-4-23 因入库通知单重构,重写此方法  此方法过时{@link AsnOrderServiceImpl#getColorList}
     * </p>
     *
     * @param whCode 仓库code
     */
    @Override
    @Deprecated
    public List<String> getColorListOld(String whCode) {
        return wmsAsnTempExpandMapper.queryColorList(whCode);
    }


    /**
     * 颜色下拉列表
     * <p>
     * 2018-4-23 因入库通知单重构,重写此方法
     * </p>
     *
     * @param whCode 仓库code
     */
    @Override
    public List<WmsWarehouseNoticeDetail> getColorList(String whCode) {
        if (logger.isInfoEnabled()) {
            logger.info("AsnOrderServiceImpl.getColorList params:{}", whCode);
        }
        if (StringUtils.isBlank(whCode)) {
            throw new BusinessException("仓库code不能为空!");
        }
        HashMap<String, Object> params = Maps.newHashMap();
        params.put("whCode", whCode);
        params.put("notDel", DeleteFlagEnum.NORMAL.getValue());
        return wmsWarehouseNoticeExtMapper.selectAllNoticeColorListByParam(params);
    }


    public List<String> getFileName(String path) {
        List<String> nameList = new ArrayList<String>();
        File f = new File(path);
        if (!f.exists()) {
            return null;
        }
        File fa[] = f.listFiles();
        for (int i = 0; i < fa.length; i++) {
            File fs = fa[i];
            nameList.add(fs.getName());
        }
        return nameList;
    }

    /*@Override
    public String allocTasks(WmsInboundOrderBO wmsInboundOrderBO,String type) {
        if (Objects.equals(wmsInboundOrderBO, null)) {
            logger.info("AsnOrderServiceImpl.wmsInboundOrderBO pageVo must not be null");
            throw new IllegalArgumentException("订单参数为空");
        }
        Map<String, Object> map = new HashMap();
        WmsInboundAsnOrder wmsInboundAsnOrder = new WmsInboundAsnOrder();
        BeanUtils.copyProperties(wmsInboundOrderBO, wmsInboundAsnOrder);
        //查询出空库位
        List<WmsLocation> noneLocationList = wmsLocationMapper.getNoneLocation(wmsInboundAsnOrder);
        if("storerStg".equals(type)){//根据货主分配库位

        }else if("locationStg".equals(type)) {//随机找到空库位进行分配
            if (CollectionUtils.isNotEmpty(noneLocationList)) {
                for(WmsLocation wmsLocation : noneLocationList){
                    if (wmsLocation.getLocLength() >= 5 && wmsLocation.getLocWidth() >= 2) { // TODO: 需要修改为当前长宽高的具体属性
                        map.put("locId", wmsLocation.getLocId());
                        map.put("LocCode", wmsLocation.getLocWhCode());
                        break;//找到库位直接退出循环
                    }
                }
            }
        }
        return new Gson().toJson(map);
    }*/
}
